package example.config;



import example.filter.AuthHandlerInterceptor;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 配置类 资源映射路径
 */
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
     //图片存放根路径
     @Value("${file.rootPath}")
     public String ROOT_PATH;
     //图片映射路径
     @Value("${file.uploadPath}")
     public String uploadPath;

     @Value("${server.port}")
     //获取主机端口
     public String port;

     @Value("${server.servlet.context-path}")
     public String contextPath;

     @Autowired
     AuthHandlerInterceptor authHandlerInterceptor;

     @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(this.uploadPath+"**").addResourceLocations("file:"+ this.ROOT_PATH);

     }
     @Override
     public void addCorsMappings(CorsRegistry registry) {
//         registry.addMapping("/**")
//                 .allowedOrigins("*")
//                 .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
//                 .allowCredentials(true)
//                 .allowedHeaders("*")
//                 .maxAge(3600);

         registry
                 .addMapping("/**")
                 //            .allowedOrigins("http://yyy.com", "http://xxx.com") //
                 // 允许跨域的域名
                 .allowedOrigins("*") // 允许所有域
                 .allowedMethods("*") // 允许任何方法（post、get等）
                 .allowedHeaders("*") // 允许任何请求头
                 .allowCredentials(true) // 允许证书、cookie
                 .exposedHeaders(HttpHeaders.SET_COOKIE)
                 .maxAge(3600L); // maxAge(3600)表明在3600秒内，不需要再发送预检验请求，可以缓存该结果
     }



     /**
      * 给除了 /login 的接口都配置拦截器,拦截转向到 authHandlerInterceptor
      */
     @Override
     public void addInterceptors(InterceptorRegistry registry) {
         registry.addInterceptor(authHandlerInterceptor)
                 .addPathPatterns("/uservue/**")
                 .excludePathPatterns("/uservue/login")
                 .excludePathPatterns("/user/**")
                 .excludePathPatterns("/file/**");
//                 .addPathPatterns("/**")
//                 .excludePathPatterns("/login");
     }

}

